package com.atguigu.gmall.product;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 李旭
 * @date 2022/1/10 15:16
 * @Description:
 *
 * 异步编排
 */
public class CompletableFutureDemo3 {

    public static void main(String[] args) throws Exception{
        ThreadPoolExecutor threadPoolExecutor =
                 new ThreadPoolExecutor(
                         5,
                         10,
                         5,
                         TimeUnit.SECONDS,
                         new ArrayBlockingQueue<>(10)
                 );


        //串行化方法
        //1:创建新线程
        CompletableFuture<Void> complateFutureDemo = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + ":上一个任务");
            return "我是上一个任务";
        }, threadPoolExecutor).thenApplyAsync(t -> {//接收上一个任务 并返回自己的返回值
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":当前任务");
            return "我是当前任务";
        }, threadPoolExecutor).thenAcceptAsync(t -> {
            System.out.println(Thread.currentThread().getName() + ":下一个任务");
        }, threadPoolExecutor).thenRunAsync(() -> {
            System.out.println(Thread.currentThread().getName() + ":下下一个任务");
        }, threadPoolExecutor);

        //
        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + ":第二个上一个任务");
            return "我是第二上一个任务";
        }, threadPoolExecutor);

        //CompletableFuture.allOf(complateFutureDemo,stringCompletableFuture).join();
        CompletableFuture.anyOf(complateFutureDemo,stringCompletableFuture).join();

        //2:创建新线程
        CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + ":我是第三上一个任务");
            return "我是第三上一个任务";
        },threadPoolExecutor);

    }
}
